package chatin.client;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.xmlrpc.XmlRpcException;

import org.apache.xmlrpc.client.XmlRpcClient;
import org.apache.xmlrpc.client.XmlRpcClientConfigImpl;
import org.apache.xmlrpc.client.XmlRpcCommonsTransportFactory;

public class ClientMediator {

    private static ClientMediator mediator;
    private static XmlRpcClient client = new XmlRpcClient();

    private ClientMediator() {
        // create configuration
        XmlRpcClientConfigImpl config = new XmlRpcClientConfigImpl();
        try {
            config.setServerURL(new URL("http://127.0.0.1:8080/xmlrpc"));
        } catch (MalformedURLException ex) {
            Logger.getLogger(ClientMediator.class.getName()).log(Level.SEVERE, null, ex);
        }
        config.setEnabledForExtensions(true);
        config.setConnectionTimeout(60 * 1000);
        config.setReplyTimeout(60 * 1000);

        setClient(config);

    }

    private void setClient(XmlRpcClientConfigImpl config) {
        // use Commons HttpClient as transport
        client.setTransportFactory(new XmlRpcCommonsTransportFactory(client));
        // set configuration
        client.setConfig(config);
    }

    public static boolean exec(String method, Object[] params) throws XmlRpcException {
        if (mediator == null) {
            mediator = new ClientMediator();
        }

        // make the a regular call
        return (Boolean) client.execute(method, params);
    }
}
